package com.person;

import com.person.mapper.UserMapper;
import com.person.pojo.User;
import com.person.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.ServerException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServerException, IOException {



        String username=request.getParameter("username");
        String password=request.getParameter("password");

        SqlSessionFactory sqlSessionFactory= SqlSessionFactoryUtils.getSqlSessionFactory();

        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);

        User user=userMapper.selectByUsername(username);

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        PrintWriter writer=response.getWriter();
        if(user!=null){
            writer.write("应有账号，注册失败");
        }else{
            userMapper.insert(username,password);
            sqlSession.commit();
            writer.write("注册成功");
        }
        sqlSession.close();


    }
    @Override
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServerException, IOException{
        this.doGet(request,response);
    }
}
